package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"message-queue_0826/api/params"
	"message-queue_0826/global"
	"message-queue_0826/internal/mobel"
	"message-queue_0826/pkg"
	"net/http"
	"time"
)

func LoginOrRegisterUser(c *gin.Context) {
	var req params.LoginOrRegisterUserForm

	err := c.ShouldBindJSON(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	get := global.RDB.Get(context.Background(), "sendSms"+req.Mobile+"loginOrRegister")

	if get.Val() != req.Sms {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "短信验证失败",
			"data":    "",
		})
		return
	}

	var user mobel.User

	user.Mobile = req.Mobile

	err = user.Login()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "登陆失败",
			"data":    err.Error(),
		})
		return
	}

	if user.Id == 0 {
		err = user.Register()
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    100000,
				"message": "注册失败",
				"data":    err.Error(),
			})
			return
		}
	}

	token := pkg.CreateJwtToken(user.Id, 24*time.Hour)

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登陆成功",
		"data":    token,
	})
}
